/**
 * 
 */
var userId, userName, userFullName, lastUserChat;
var routingKey = "slug.chat.";
var exchangeName = "amp.topic";
var userChatArr = new Array();
var subscriptions = {};
var client, client2, destination, destination2;
var ws, ws2 = null;

$(document).ready(function(){
	var supported = ("WebSocket" in window);
    if (!supported) {
        var msg = "Your browser does not support Web Sockets. This example will not work properly.<br>";
        msg += "Please use a Web Browser with Web Sockets support (WebKit or Google Chrome).";
        $("#connect").html(msg);
    }

    userId = $("#cht-userId").val();
    userName = $("#cht-userName").val();
    userFullName = $("#cht-userFullName").val();

	var destId = $("#cht-destId").val();
	var destType = $("#cht-destType").val();
	if (destType == "group") {
		destination = "/topic/" + routingKey + destId;
		destination2 = "";
	} else {
		destination = "/topic/" + routingKey + (userId + "-" + destId);
		destination2 = "/topic/" + routingKey + (destId + "-" + userId);
	}
    
	createWSConnection(destination);
	createWSConnection2(destination2);
});

function createWSConnection(destination){
	if(ws != null){
		ws.close();
	}
    var url = "http://172.16.21.60:15674/stomp";
    var login = "guest";
    var passcode = "guest";
    
	ws = new SockJS(url);
    client = Stomp.over(ws);
    
    // this allows to display debug logs directly on the web page
    client.debug = function (str) {
        console.log(str)
    };
    
    // the client is notified when it is connected to the server.
    var onconnect = function (frame) {
        client.debug("connected to Stomp");

        client.subscribe(destination, function(message){
        	stopTimer();
            var p = document.createElement("li");
            
            var json = $.parseJSON(message.body);

            var leftOrRight = (userId == json.ownerId ? 'left' : 'right');
            var rightOrLeft = (userId == json.ownerId ? 'right' : 'left');
            
            var att=document.createAttribute("class");
            att.value=leftOrRight+" clearfix";
            p.setAttributeNode(att);
            if(lastUserChat == json.ownerId){
                k = document.createElement("p");
        	    k.innerHTML = json.content;
        	    $("#messages > li:last-child > div.chat-body").append(k);
            }else{
                txt =	'<span class="chat-img pull-'+leftOrRight+'">'+
        					'<img src="https://i0.wp.com/developer.files.wordpress.com/2013/01/60b40db1e3946a29262eda6c78f33123.jpg?w=40" alt="User Avatar" class="img-circle" />'+
        				'</span>'+
        				'<div class="chat-body clearfix">'+
        					((userId == json.ownerId) 
        						? 
        						('<div class="header">'+
        							'<strong class="primary-font">'+json.ownerName+'</strong>'+
        							'<small class="pull-right text-muted">'+
        								'<span class="glyphicon glyphicon-time"></span><span class="time-ago" id="'+json.datetime+'">'+calculateTime(json.datetime)+
        							'</span></small>'+
        						'</div>')
        						:
        						('<div class="header">'+
        							'<small class="text-muted">'+
        								'<span class="glyphicon glyphicon-time"></span><span class="time-ago" id="'+json.datetime+'">'+calculateTime(json.datetime)+
        							'</span></small>'+
        							'<strong class="pull-right primary-font">'+json.ownerName+'</strong>'+
        						'</div>')
        					)+
        					'<p>'+
        						json.content+
        					'</p>'+
        				'</div>';
                p.innerHTML = txt;
                $("#messages").append(p);
            }

            lastUserChat = json.ownerId
            startTimer();
            
            // Scroll to bottom chat
        	var objDiv = document.getElementById("conversation-cover");
        	objDiv.scrollTop = objDiv.scrollHeight;
        }, subscriptions);
    };
    
    var onerror = function () {
        console.log('error');
    };
    var headers = {
        login: login,
        passcode: passcode,
        'Content-Type': 'text/html; charset=utf-8'
        // additional header
        // 'client-id': 'client-id-' + userId,
        // 'Access-Control-Allow-Origin': '*'
    };
    client.heartbeat.outgoing = 0;
    client.heartbeat.incoming = 0;
    client.connect(headers, onconnect, onerror);
}

function createWSConnection2(destination2){
	if(ws2 != null){
		ws2.close();
	}
	
	if(destination2 == ""){
		return;
	}
    var url = "http://172.16.21.60:15674/stomp";
    var login = "guest";
    var passcode = "guest";
    
	ws2 = new SockJS(url);
    client2 = Stomp.over(ws2);
    
    // this allows to display debug logs directly on the web page
    client2.debug = function (str) {
        console.log(str)
    };
    
    // the client is notified when it is connected to the server.
    var onconnect2 = function (frame) {
        client2.debug("connected to Stomp");

        client2.subscribe(destination2, function(message){
        	stopTimer();
            var p = document.createElement("li");
            
            var json = $.parseJSON(message.body);

            var leftOrRight = (userId == json.ownerId ? 'left' : 'right');
            var rightOrLeft = (userId == json.ownerId ? 'right' : 'left');
            
            var att=document.createAttribute("class");
            att.value=leftOrRight+" clearfix";
            p.setAttributeNode(att);
            if(lastUserChat == json.ownerId){
                k = document.createElement("p");
        	    k.innerHTML = json.content;
        	    $("#messages > li:last-child > div.chat-body").append(k);
            }else{
                txt =	'<span class="chat-img pull-'+leftOrRight+'">'+
        					'<img src="https://i0.wp.com/developer.files.wordpress.com/2013/01/60b40db1e3946a29262eda6c78f33123.jpg?w=40" alt="User Avatar" class="img-circle" />'+
        				'</span>'+
        				'<div class="chat-body clearfix">'+
        					((userId == json.ownerId) 
        						? 
        						('<div class="header">'+
        							'<strong class="primary-font">'+json.ownerName+'</strong>'+
        							'<small class="pull-right text-muted">'+
        								'<span class="glyphicon glyphicon-time"></span><span class="time-ago" id="'+json.datetime+'">'+calculateTime(json.datetime)+
        							'</span></small>'+
        						'</div>')
        						:
        						('<div class="header">'+
        							'<small class="text-muted">'+
        								'<span class="glyphicon glyphicon-time"></span><span class="time-ago" id="'+json.datetime+'">'+calculateTime(json.datetime)+
        							'</span></small>'+
        							'<strong class="pull-right primary-font">'+json.ownerName+'</strong>'+
        						'</div>')
        					)+
        					'<p>'+
        						json.content+
        					'</p>'+
        				'</div>';
                p.innerHTML = txt;
                $("#messages").append(p);
            }

            lastUserChat = json.ownerId
            startTimer();
            
            // Scroll to bottom chat
        	var objDiv = document.getElementById("conversation-cover");
        	objDiv.scrollTop = objDiv.scrollHeight;
        }, subscriptions);
    };
    
    var onerror2 = function () {
        console.log('error');
    };
    var headers2 = {
        login: login,
        passcode: passcode,
        'Content-Type': 'text/html; charset=utf-8'
        // additional header
        // 'client-id': 'client-id-' + userId,
        // 'Access-Control-Allow-Origin': '*'
    };
    client2.heartbeat.outgoing = 0;
    client2.heartbeat.incoming = 0;
    client2.connect(headers2, onconnect2, onerror2);
}

function chat(){
    var msg = JSON.stringify(createMessageChat());
    client.send(destination, {}, msg);
    $("#cht-message").val("");
	return false;
}

function createMessageChat(){
	var message = $("#cht-message").val();
	var destId = $("#cht-destId").val();
	var destType = $("#cht-destType").val();
	var usr = new Object();
    usr.ownerId = userId;
    usr.ownerName = userFullName;
    usr.datetime = new Date().getTime(); 
    usr.content = message;
    usr.contentType = "text";
    usr.messageType = "chat";
    usr.destinateId = destId;
    usr.destinateType = destType;
    
    if(destType == "group"){
    	usr.routingKey = routingKey + destId;
    }else{
    	usr.routingKey = routingKey + userId + "-" + destId;
    }
	usr.exchangeName = exchangeName;
	return usr;
}

function calculateTime(timestamp){
	var now = new Date().getTime();
	var subTime = new Date().getTime() - timestamp;

	var oYear = 365 * 24 * 60 * 60 * 1000;
	var oMonth = 30 * 24 * 60 * 60 * 1000;
	var oDay = 24 * 60 * 60 * 1000;
	var oHour = 60 * 60 * 1000;
	var oMin = 60 * 1000;
	
	// years
	if(subTime > oYear){
		return Math.floor(subTime/oYear) + " years ago";
		
	// months
	}else if(subTime > oMonth){
		return Math.floor(subTime/oMonth) + " months ago";
		
	// days
	}else if(subTime > oDay){
		return Math.floor(subTime/oDay) + " days ago";
		
	// hours
	}else if(subTime > oHour){
		return Math.floor(subTime/oHour) + " hours ago";
		
	// mins
	}else if(subTime > oMin){
		return Math.floor(subTime/oMin) + " mins ago";
	}else{
		return "a few seconds ago";
	}
}

function chatwith(destId, destType, destName){
	$("#conv-title").html(destName);
	$("#cht-destId").val(destId);
	$("#cht-destType").val(destType);
	$.ajax({
		url: '/chatWith',
		type: 'POST',
		data: $.stringify({"destId": destId, "destType": destType}),
		dataType: 'json',
		contentType: "application/json; charset=utf-8",
		success: function(data) {
			$("#messages").html(data.message);
			var objDiv = document.getElementById("conversation-cover");
			objDiv.scrollTop = objDiv.scrollHeight;
			
			if (destType == "group") {
				destination = "/topic/" + routingKey + destId;
				destination2 = "";
			} else {
				destination = "/topic/" + routingKey + (userId + "-" + destId);
				destination2 = "/topic/" + routingKey + (destId + "-" + userId);
			}
			
			createWSConnection(destination);
			createWSConnection2(destination2);
			// called when successful
			// var json = $.parseJSON(data);
			// alert(data.message);
		},
		error : function(e) {
			// called when there is an error
			// var json = $.parseJSON(data);
			// alert(data.message);
		}
	});
}

/** Timer */
var timer = setInterval(function(){countTimer()}, 10000);
function countTimer() {
    $(".time-ago").each(function(){
    	$(this).html(calculateTime(this.id));
    });
}

function startTimer() {
	timer = setInterval(function(){countTimer()}, 10000);
}

function stopTimer() {
    clearInterval(timer);
}